//
//  KKHomeTableViewController.swift
//  SinaWeiBo
//
//  Created by King.Kong. on 16/5/19.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit
import SVProgressHUD

let HomeCellId = "HomeCellId"

class KKHomeTableViewController: KKBaseTableViewController {
    // 模型数据
//   private lazy var statuses: [KKStatus] = [KKStatus]()
    //自定义下拉刷新控件
    let refreshView = KKRefreshControl()

    lazy var statusListViewModel:KKStatusListViewModel = KKStatusListViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin {
            //用户未登录 设置访客视图的信息
            //TODO:解决第一次登陆 fatal error: unexpectedly found nil while unwrapping an Optional value
            visitorLoginView.updateUI("关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon",isHome: true)
            return
        }
        
        setNav()
      
        prepareForTableView()
        
        loadData()
    }
    
    private func prepareForTableView() {
        
        // 注册tableView
        tableView.registerClass(KKStatusCell.self, forCellReuseIdentifier: HomeCellId)
        
        //设置cell的高度 固定行高
//        tableView.rowHeight = 300
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置预估行高  行高的自动计算
        //提高tableView加载效率 预估行高 * 数据源的数量 = contentSize  -> tableView才可以滚动
        tableView.estimatedRowHeight = 300
        
        //设置分割线
        tableView.separatorStyle = .None
        
        //添加自定义刷新控件
//        let refreshView = KKRefreshControl()

        //添加初始响应的事件
        refreshView.addTarget(self, action: #selector(KKHomeTableViewController.loadData), forControlEvents: .ValueChanged)
        
        //添加到tableView上
        self.tableView.addSubview(refreshView)

        //添加到导航条上
        self.navigationController?.navigationBar.addSubview(tipLabel)
        //移动最底层
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)

        //设置小菊花 talbeView的tableViewFooterView
        tableView.tableFooterView = pullupView

    }
    private func setNav() {
        
        let pushItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(KKHomeTableViewController.push))
        navigationItem.rightBarButtonItem = pushItem
    
    }
    
    
    @objc private func push() {
        
        let detailVc = KKDetailViewController()
//        detailVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(detailVc, animated: true)
    
    }
    
    //小菊花控件
    private lazy var pullupView: UIActivityIndicatorView = {
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        //初始的时候做动画
        
        return indicatorView
    }()
    
    private lazy var tipLabel: UILabel = {
        let l = UILabel(title: "", textColor: UIColor.whiteColor(), font: 15)
        
        l.frame = CGRect(x: 0, y: -64, width: ScreenWidth, height: 40)
        //设置背景颜色
        l.backgroundColor = UIColor.orangeColor()
        return l
    }()


}

// MARK: 加载数据
extension KKHomeTableViewController {
   @objc private func loadData() {

    //停止小菊花的转动
    self.refreshControl?.endRefreshing()

    
    statusListViewModel.loadData(pullupView.isAnimating()) { (isSuccess,count) in

        //停止小菊花的转动
//        self.refreshControl?.endRefreshing()
        self.refreshView.endRefreshing()

        if !isSuccess {
           SVProgressHUD.showWithStatus(AppErrorTip)
            return
        }
        
        if self.pullupView.isAnimating() {
            //静默加载数据
            self.pullupView.stopAnimating()
        } else {
            //下拉刷新数据
            //提示用户刷新了多少条数据
            self.startAnimation(count)
        }

        // 回调成功 刷新数据
        self.tableView.reloadData()
    }
    }
    //提示用户刷新多少条数据
    private func startAnimation(count: Int) {
        let tipText = (count == 0) ? "没有新数据" : "有\(count)条新数据"
        tipLabel.text = tipText
        //开始动画
        let rect = tipLabel.frame
        UIView.animateWithDuration(0.6, animations: {
            self.tipLabel.frame = CGRect(x: 0, y: 44, width: ScreenWidth, height: 40)
        }) { (_) in
            //print("OK")
            //执行闭包动画 回到从前
            UIView.animateWithDuration(0.3, delay: 1, options: [], animations: {
                self.tipLabel.frame = rect
                }, completion: { (_) in
                    print("👌")
            })
        }
    }

}

// MARK:实现数据源方法
extension KKHomeTableViewController {
    
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statusListViewModel.statusViewModelArray.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath) as! KKStatusCell

        // //如果正在加载最后一行cell的时候 && 没有转动的时候 开始加载老数据
        if indexPath.row == statusListViewModel.statusViewModelArray.count - 1 && !pullupView.isAnimating() {
            print("开始执行静默加载")
            pullupView.startAnimating()
            
            //加载数据
            loadData()
        }
        cell.statusViewModel = statusListViewModel.statusViewModelArray[indexPath.row]
        
        return cell
    }
    

    
}
